package cn.com.elite;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class mailrun implements Runnable{
	private static final Log log=LogFactory.getLog(mailrun.class);
	public static String address=""; //用于发送EMAIL的发送者地址 
	public static String username=""; //发送者的用户名 
	public static String password=""; //发送者的密码 
	public static String SMTPHost=""; //IP
	public static String mail_sql=""; //查询MAIL的SQL语句
	public static String eml_path="";  //存放临时EML文件的地址
	public static String f_path="";   //存放临时附件的地址
	public static String dotime="";   //运行时间
	public static String systemcode="";
	public static cn.com.elite.MailBean mailbean;
	
	
	
	public static String url="";
	public static String requestType1="";
	public static String requestType2="";
	public static String user="";
	public static String password1="";
	public static String usercode="";
	public static String comcode="";
	
	private static SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
	
	public static String getSystemcode() {
		return systemcode;
	}
	public static void setSystemcode(String systemcode) {
		mailrun.systemcode = systemcode;
	}
	public static String getUrl() {
		return url;
	}
	public static void setUrl(String url) {
		mailrun.url = url;
	}
	public static String getRequestType1() {
		return requestType1;
	}
	public static void setRequestType1(String requestType1) {
		mailrun.requestType1 = requestType1;
	}
	public static String getRequestType2() {
		return requestType2;
	}
	public static void setRequestType2(String requestType2) {
		mailrun.requestType2 = requestType2;
	}
	public static String getUser() {
		return user;
	}
	public static void setUser(String user) {
		mailrun.user = user;
	}
	public static String getPassword1() {
		return password1;
	}
	public static void setPassword1(String password1) {
		mailrun.password1 = password1;
	}
	public static String getUsercode() {
		return usercode;
	}
	public static void setUsercode(String usercode) {
		mailrun.usercode = usercode;
	}
	public static String getComcode() {
		return comcode;
	}
	public static void setComcode(String comcode) {
		mailrun.comcode = comcode;
	}
	public static String getDotime() {
		return dotime;
	}
	public static void setDotime(String dotime) {
		mailrun.dotime = dotime;
	}
	public static String getMail_sql() {
		return mail_sql;
	}
	public static void setMail_sql(String mail_sql) {
		mailrun.mail_sql = mail_sql;
	}
	public static String getAddress() {
		return address;
	}
	public static void setAddress(String address) {
		mailrun.address = address;
	}
	public static String getUsername() {
		return username;
	}
	public static void setUsername(String username) {
		mailrun.username = username;
	}
	public static String getPassword() {
		return password;
	}
	public static void setPassword(String password) {
		mailrun.password = password;
	}
	public static String getSMTPHost() {
		return SMTPHost;
	}
	public static void setSMTPHost(String host) {
		SMTPHost = host;
	}
	public static cn.com.elite.MailBean getMailbean() {
		return mailbean;
	}
	public static void setMailbean(cn.com.elite.MailBean mailbean) {
		mailrun.mailbean = mailbean;
	}
	public static void main(String[] args){
//		String a="<?xml version='1.0' encoding='UTF-8'?><PACKET type='RESPONSE' version='1.0'><HEAD><REQUEST_TYPE>002</REQUEST_TYPE><RESPONSE_CODE>1</RESPONSE_CODE><ERROR_MESSAGE></ERROR_MESSAGE></HEAD><BODY><Request>  <uuid>4d31d217-d19b-4e7a-b93d-59f91e2af965</uuid>  <fromNumber>13524267334</fromNumber>  <toNumber>13524267334</toNumber>  <sendTime>2012-02-10 15:57:48.906 CST</sendTime>  <content>路是一步一步走出来的。爱是一点一点换回来的。人生也是这样一页一页真真实实活下去的！我珍惜我的人生，更加珍惜你！【三星财产保险】</content>  <systemCode>TM</systemCode>  ";

		 String a="<?xml version='1.0' encoding='UTF-8'?><PACKET type='RESPONSE' version='1.0'><HEAD><REQUEST_TYPE>002</REQUEST_TYPE><RESPONSE_CODE>E</RESPONSE_CODE><ERROR_MESSAGE>Error in UserName or Password</ERROR_MESSAGE></HEAD><BODY/></PACKET>";

		System.out.println(parserXml(a));
	}
	public static String parserXml(String inputXml){
		try{
			Document document=DocumentHelper.parseText(inputXml);
	        Element ossresponse=(Element) document.getRootElement();
            for(Iterator i=ossresponse.elementIterator();i.hasNext();){
            	Element CustomerInfo=(Element)i.next();
            	if(CustomerInfo.getName().equals("HEAD")){
            		for(Iterator t=CustomerInfo.elementIterator();t.hasNext();){
            			Element attribute=(Element)t.next();
    	            	String name=attribute.getName();
    	            	if(name.equals("RESPONSE_CODE")){
    	            		return attribute.getText();
    	            	}
            		}
            	}
            }      
	        return "wrong2";
		}catch(Exception e){
			log.error(getERRO(e));
			return "wrong3";
		}
	}
	
	public static String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw = new StringWriter();  
            e.printStackTrace(new PrintWriter(sw, true));  
            str = sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}
	public String Stringutil(String a){
		if(a==null){
			return "";
		}else{
			return a;
		}
	}
	public void dorun2(){
		try{
		List list=getmail();
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				Map map=(Map)list.get(i);
				log.info("map:"+map);
				String path=(String)map.get("documentpath");
				String documentout_guid=(String)map.get("documentout_guid");
				String DocumentTo=(String)map.get("DocumentTo");
				String Documentfrom=(String)map.get("DocumentTo");
				BigDecimal doctype1=(BigDecimal)map.get("doctype");
				String businesstype=(String)map.get("stringfield2");
				log.info("run_stringfield2:"+businesstype);
				log.info("run_systemcode:"+systemcode);
				log.info("documentout_guid:"+documentout_guid);
				int doctype=doctype1.intValue();
				String comments=Stringutil((String)map.get("comments"));
				if(doctype==2){      //邮件aaa
					log.info("邮件:"+documentout_guid);
					try{						
						MailImplTest mail=new MailImplTest();
						String project=(String)map.get("project");
						String comments1=Stringutil((String)map.get("comments1"));
						String comments2=Stringutil((String)map.get("comments2"));
						comments=comments+comments1+comments2;
						String result=mail.SendMail(project,url,requestType2,user,password1,address,DocumentTo,comments,usercode,comcode,getattach(documentout_guid),businesstype,systemcode);
						log.info("sms_result:"+result);
						String sql="update  documentout set status=1,finishdatetime=sysdate,modifieddate=sysdate where documentout_guid='"+documentout_guid+"'";
						log.info("更新documentout表语句:"+sql);
						log.info("更新documentout表记录:"+mailbean.update(sql));
					}catch(Exception e){
						String sql="update  documentout set status=1,finishdatetime=sysdate,modifieddate=sysdate where documentout_guid='"+documentout_guid+"'";
						log.info("更新documentout表语句:"+sql);
						log.info("更新documentout表记录:"+mailbean.update(sql));
						log.error(getERRO(e));
					}
				}else if(doctype==3){     //短信
					log.info("短信:"+documentout_guid);
					String sql="";
					try{
						SmsImplTest sms=new SmsImplTest();
						String result=sms.SendSms(url,requestType1,user,password1,Documentfrom,DocumentTo,path,businesstype,systemcode,documentout_guid);
						log.info("sms_result:"+result);
						String result_code=parserXml(result);
						log.info("result_code:"+result_code);
						if(result_code.equals("1")){
							sql="update  documentout set status=1,finishdatetime=sysdate,modifieddate=sysdate where documentout_guid='"+documentout_guid+"'";
						}else{
							sql="update  documentout set TrialCount=TrialCount+1,modifieddate=sysdate,LastTryDateTime=sysdate where documentout_guid='"+documentout_guid+"'";
						}						
					}catch(Exception e){
						sql="update  documentout set TrialCount=TrialCount+1,modifieddate=sysdate,LastTryDateTime=sysdate where documentout_guid='"+documentout_guid+"'";
						log.error(getERRO(e));
					}
					try{
						log.info("更新documentout表语句:"+sql);
						log.info("更新documentout表记录:"+mailbean.update(sql));
					}catch(Exception e){
						log.error(getERRO(e));
					}
				}
				
			}
		}else{
//			log.info("无纪录");
		}
		}catch(Exception e){
			log.error(getERRO(e));
		}
	}
	public void run(){
		while(true){
			dorun2();
			try {
				Thread.sleep(Integer.parseInt(dotime)*1000);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				log.info("Thread.sleep失败"+e);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				log.info("Thread.sleep失败"+e);
			} 
		}
		
	}
	public void dorun1(FTPClient ftp){
		List list=getmail();
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				Map map=(Map)list.get(i);
				String path=(String)map.get("documentpath");
				String documentout_guid=(String)map.get("documentout_guid");
				log.info("documentpath:"+path);
				String flag=downloadfile(path,eml_path,ftp);
				log.info("downloadfile是否成功:"+flag);
				if(!flag.equals("fail")){
					ReadEmail readmail=new ReadEmail();
					Map map1=readmail.readmail(flag, f_path);
					MailSend mailsend=new MailSend();
					boolean aa=mailsend.send(address,SMTPHost,username,password,map1);
					if(aa==true){
						String sql="update  documentout set status=1,finishdatetime=sysdate,modifieddate=sysdate where documentout_guid='"+documentout_guid+"'";
						log.info("更新documentout表语句:"+sql);
						log.info("更新documentout表记录:"+mailbean.update(sql));
					}else{
						log.info("发送失败documentout_guid:"+documentout_guid);
					}
				}else{
					log.info("downloadfile失败");
				}
			}
		}else{
			log.info("无MIAL_LIST");
		}
		FTPCLOSE(ftp);
	}
	public void dorun(){
		String FTPOUT=getFTPOUT();
		String[] param=FTPOUT.split(",");
		log.info("获得FTPOUT:"+FTPOUT);
		FTPClient ftp=null;
        if(param.length==3){
        	ftp=GetFtp(param[0],Integer.parseInt(param[1]),param[2],"");
        	dorun1(ftp);
        }else if(param.length>3){
			ftp=GetFtp(param[0],Integer.parseInt(param[1]),param[2],param[3]);
			dorun1(ftp);			
		}else{
			log.info("获得FTPOUT失败");
		}
		
	}
	private static boolean tofile(File newfile,FTPClient ftp,String path){
		FileOutputStream fos=null;
		try {
			fos = new FileOutputStream(newfile);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			log.info("获得FileOutputStream失败:"+e1);
		}
		boolean flag=false;
		try {
			log.info("path:"+path);
			String path1=path.substring(1, path.length());
			log.info("path1:"+path1);
			flag = ftp.retrieveFile(path1,fos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.info("ftp.retrieveFile失败:"+e);
		}
		log.info("下载EML文件是否成功:"+flag);
		return flag;
		
	}
	private static String downloadfile(String path,String eml_path,FTPClient ftp){
		String newpath=eml_path+"/"+getfilename(path);
		boolean flag=false;
		log.info("下载文件的新路径:"+newpath);
		File newfile=new File(newpath); 
		if(newfile.exists()){
			boolean a=newfile.delete();
			log.info("删除旧文件是否成功:"+a);
			flag=tofile(newfile,ftp,path);
			log.info("tofile是否成功:"+flag);
		}else{
			flag=tofile(newfile,ftp,path);
			log.info("tofile是否成功:"+flag);
		}		
		if(flag==true){
			return newpath;
		}else{
			return "fail";
		}
	}
	private static String getfilename(String path){
		String a=path.substring(path.lastIndexOf("/")+1,path.length());
		return a;
	}
	
	private static List getattach(String guid){
		List list=null;
		try {
			list=mailbean.chaxun("select path from documentout_path where documentout_guid='"+guid+"' ");
		} catch (Exception e) {
			log.info("查询maillist失败:"+e);
		}
		return list;
	}
	
	private static List getmail(){
		List list=null;
		try {
			list=mailbean.chaxun(mail_sql);
		} catch (Exception e) {
			log.info("查询maillist失败:"+e);
		}
		return list;
	}
	private static String getFTPOUT(){
		String sql="select PARAMETERVALUE from sysc_parameter where PARAMETER_ID='FTPOUT'";
		log.info("查询FTPOUT:"+sql);
		String FTPOUT="";
		try {
			FTPOUT=mailbean.chaxun1(sql);
		} catch (Exception e) {
			log.info("查询FTPOUT失败:"+e);
		}
		return FTPOUT;
	}
	private static FTPClient GetFtp(String host,int port,String username1,String password1){
		FTPClient ftp;
		ftp = new FTPClient(); 
		try{
			ftp.connect(host,port);
			log.info("host:"+host);
			log.info("port:"+port);
			ftp.setControlEncoding("GBK");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			log.info("username:"+username1);
			log.info("password:"+password1);
			ftp.login(username1,password1);
		}catch(Exception e){
			log.info("FTP连接失败:"+e);
		}
		return ftp;
	}
	private static void FTPCLOSE(FTPClient ftp){
		try {
			ftp.logout();
		} catch (IOException e) {
			log.info("ftp.logout():"+e);
		}
		try {
			ftp.disconnect();
		} catch (IOException e) {
			log.info("ftp.disconnect():"+e);
		}
	}
	public static String getEml_path() {
		return eml_path;
	}
	public static void setEml_path(String eml_path) {
		mailrun.eml_path = eml_path;
	}
	public static String getF_path() {
		return f_path;
	}
	public static void setF_path(String f_path) {
		mailrun.f_path = f_path;
	}
}
